import React, { useState, useEffect, useRef, MutableRefObject } from 'react'

export default function useTime(second: number) {
  const [num, setNum] = useState(second)
  const [flag, setFlag] = useState(false)
  const Timer = useRef<NodeJS.Timeout | undefined>()

  useEffect(() => {
    djs()

    return () => {
      clearInterval(Timer.current)
    }
  }, [])
  function djs() {
    Timer.current = setInterval(() => {
      setNum(pre => {
        if (pre <= 1) {
          clearInterval(Timer.current)
          setFlag(true)
        }
        return pre - 1
      })
    }, 1000)
  }
  return (
    <>
      <div
        style={{
          border: '1px solid',
          borderRadius: '50%',
          width: '100px',
          height: '100px',
          position: 'relative',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >
        {num}
      </div>
      <button
        onClick={() => {
          setFlag(pre => {
            if (pre && num <= 0) {
              setNum(second)
              djs()
            } else if (pre && num >= 0) {
              djs()
            } else if (!pre) {
              clearInterval(Timer.current)
            }
            return !pre
          })
        }}
      >
        {flag ? '开始' : '暂停'}
      </button>
    </>
  )
}
interface TableItemBody {
  [fieldId: string]: string
}

interface TableItem {
  [tabId: string]: TableItemBody | TableItemBody[]
}

const iterate = (entry: TableItem) => {
  for (const tabId of Object.keys(entry)) {
    if (Array.isArray(entry[tabId])) {
      const tableItems = entry[tabId] as TableItemBody[]
      for (const idx of tableItems) {
        for (const fieldId of Object.keys(tableItems)) {
          console.log(fieldId)
        }
      }
    } else {
      for (const fieldId of Object.keys(entry[tabId])) {
        console.log(fieldId)
      }
    }
  }
}

const tableItem: TableItem = {
  tab1: {
    field1: 'fieldValue',
  },
  tab2: [
    {
      field2: 'fieldValue',
    },
  ],
}

iterate(tableItem)
